package com.yaoge.agent.annotation;

import java.lang.reflect.Field;

public class MainTest {
    public static void main(String[] args) {
        Person person = new Person("zhangsan", "男", "河南信阳", 100);


        try {
            boolean isTrue = check(person);
            if (isTrue){
                System.out.println("参数没有错误");
            }else {
                System.out.println("参数有误");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    public static boolean check(Person person) throws IllegalAccessException {


        Class aClass = person.getClass();


        boolean isTrue = true;
        for (Field field : aClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(Range.class)) {
                Range range = field.getAnnotation(Range.class);

                field.setAccessible(true);
                Object value = field.get(person);

                if (value instanceof String) {

                    String s = (String) value;
                    if (s.length() < range.min() || s.length() > range.max()) {

                        isTrue = false;

                        throw new IllegalArgumentException("参数：" + field.getName() + "不在范围之内 ");

                    }

                } else if (value instanceof Integer) {

                    int i = (Integer) value;

                    if (i < range.min() || i > range.max()) {

                        isTrue = false;

                        throw new IllegalArgumentException("参数：" + field.getName() + "不在范围之内" + "要求参数在 " + range.max() + "和" + range.min() + "之间");

                    }
                }

            }
        }


        return isTrue;
    }
}
